// 云函数模板
// 部署：在 cloud-functions/login 文件夹右击选择 “上传并部署”

const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database({
  throwOnNotFound: false
})

/**
 * 这个示例将经自动鉴权过的小程序用户 openid 返回给小程序端
 * 
 * event 参数包含小程序端调用传入的 data
 * 
 */
exports.main = async (event, context) => {
  await initUser(event, context)
  const data = await initUser(event, context)
  return data
}

const initUser = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let {
    data: user
  } = await db.collection('user').doc(wxContext.OPENID).get()
  if (!user) {
    user = {
      _id: wxContext.OPENID,
      addTime: Date.now(),
      _opendId: wxContext.OPENID,
    }
    db.collection('user').add({
      data: user
    })
  }
  return {
    user: user,
  }
}